/**
* common functions
* copyright@Catosoft.com reserved, 2016
* 2016.06.16, created by Eric.Wang
*/

if ( !Array.prototype.forEach ) {

  Array.prototype.forEach = function forEach( callback, thisArg ) {

    var T, k;

    if ( this == null ) {
      throw new TypeError( "this is null or not defined" );
    }
    var O = Object(this);
    var len = O.length >>> 0; 
    if ( typeof callback !== "function" ) {
      throw new TypeError( callback + " is not a function" );
    }
    if ( arguments.length > 1 ) {
      T = thisArg;
    }
    k = 0;

    while( k < len ) {

      var kValue;
      if ( k in O ) {

        kValue = O[ k ];
        callback.call( T, kValue, k, O );
      }
      k++;
    }
  };
}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;
    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

if ('function' !== typeof Array.prototype.reduce) {
  Array.prototype.reduce = function(callback, opt_initialValue){
    'use strict';
    if (null === this || 'undefined' === typeof this) {
      // At the moment all modern browsers, that support strict mode, have
      // native implementation of Array.prototype.reduce. For instance, IE8
      // does not support strict mode, so this check is actually useless.
      throw new TypeError(
          'Array.prototype.reduce called on null or undefined');
    }
    if ('function' !== typeof callback) {
      throw new TypeError(callback + ' is not a function');
    }
    var index, value,
        length = this.length >>> 0,
        isValueSet = false;
    if (1 < arguments.length) {
      value = opt_initialValue;
      isValueSet = true;
    }
    for (index = 0; length > index; ++index) {
      if (this.hasOwnProperty(index)) {
        if (isValueSet) {
          value = callback(value, this[index], index, this);
        }
        else {
          value = this[index];
          isValueSet = true;
        }
      }
    }
    if (!isValueSet) {
      throw new TypeError('Reduce of empty array with no initial value');
    }
    return value;
  };
}



// ajax request
var createAjax = function(option, fn){
	var option = option || {};
	var url = option.url;
	var type = option.type || 'GET';
	var data = option.data || {};
	data.projectcode = '0213202012041';
	data.pursuercodes = '01,02,03,04';

	var _baseURL = 'http://120.26.101.146:8089';
	url = _baseURL + url;

	$.ajax({
		url: url,
		type: type,
		data: data,
		dataType: 'json',
		success: function(data){
			if(typeof fn !== 'function'){
				return ;
			}
			if(data.code != 0){
				fn(data);
			}else{
				fn(null, data.data);
			}
		},
		error: function(err){
			fn(err);
			console.error(err);
		}
	});
}

// array sort by option
var compare = function(option){
	if(option.sort != 'asc' && option.sort != 'desc'){
		console.error('option invalid');
		return ;
	}
	var sort = option.sort == 'asc' ? false : true;
	return function(param1, param2){
		if(param1[option.attr] > param2[option.attr]){
			return sort;
		}else if(param1[option.attr] < param2[option.attr]){
			return !sort;
		}else{
			return 0;
		}
	}
}

// get export menus
var getMenuItems = function(param){
	var items = ['print', 'separator', 'toPNG', 'toJPEG', 'toPDF'];
	var menuItems = [];
	if(param && Object.prototype.toString.call(param) == '[object Array]' && param.length > 0){
		items = param;
	}
	$.each(items, function(index, item){
		if(buttons[item]){
			menuItems.push(buttons[item]);
		}
	});
	return menuItems;
}

// column chart filter
var columnFilter = function(data, series, categories){
	$.each(data, function(index, item){
		categories.push(item.name);
		$.each(series, function(index, each){
			each.data.push(item[each.identifier]);
		});
	});
}

// sum formatter for table footer
function sumFormatter(data){
    var field = this.field;

    var total_sum = data.reduce(function(sum, row){
        return (sum) + (parseFloat(row[field]) || 0);
    }, 0);

    return total_sum;
}

function createSelectBoxByCategories(categories) {
	var html = '<select class="form-control select-column-chart">';
	html += '<option value="-1">--查看全部--</option>';
	categories.forEach(function (name, index) {
		html += '<option value="' + index + '">' + name + '</option>';
	});
	html += '</select>';

	return html;
}

function onChartSelectChanged(categories, chart, seriesData) {
	var target = (event.currentTarget) ? event.currentTarget : event.srcElement;
	var index = +target.value;

	if (index === -1) {
		seriesData.forEach(function (data, i) {
			var yData = [];

			data.forEach(function (value) {
				yData.push({ y: value });
			});

			chart.series[i].setData(yData);
		});
		chart.xAxis[0].setCategories(categories);
	} else {
		seriesData.forEach(function (data, i) {
			chart.series[i].setData([{y: data[index]}]);
		});
		chart.xAxis[0].setCategories([categories[index]]);
	}
};

function bindSelect(element, chart, filter) {
	$('#' + element).prepend(createSelectBoxByCategories(filter.categories));

	seriesData = [];
	filter.series.forEach(function (serie, index) {
		seriesData[index] = [];
		serie.data.forEach(function (value) {
			seriesData[index].push(value);
		});
	});
	$('#' + element + ' .select-column-chart').on('change', (function (categories, chart, seriesData) {
		return function () {
			onChartSelectChanged(categories, chart, seriesData);
		}
	})(filter.categories, chart, seriesData));
}